package com.fumin.common;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

/**
 * 获取Spring的上下文,和获取被spring管理的bean对象
 * @Author xiayuxuanmin
 * @Date 2019/10/18
 * @Description
 */
@Component("applicationContextHelper")
public class ApplicationContextHelper implements ApplicationContextAware {

    private static ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext context) throws BeansException {
        applicationContext = context;
    }

    /**
     * 根据对象类型,从spring上下文中获取该对象的实例
     * @param clazz 对象的class对象
     * @param <T>  对象的类型
     * @return
     */
    public static <T> T popBean(Class<T> clazz){
        if (applicationContext == null) {
            return null;
        }
        return applicationContext.getBean(clazz);
    }

    /**
     * 根据对象类型,从spring上下文中获取该对象的实例
     * @param name spring管理的bean的名字
     * @param clazz 对象的class对象
     * @param <T> 对象的类型
     * @return
     */
    public static <T> T popBean(String name,Class<T> clazz){
        if (applicationContext == null) {
            return null;
        }
        return applicationContext.getBean(name,clazz);
    }
}
